import { asyncRoutes, constantRoutes } from '@/router'
import { getPermission } from '@/api/user'
import store from '../index'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }

    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}
let aliasChildren = [];
// 过滤出有权限的
function filterPermissionRoute(parentPath, permissionNames = [], routes = []) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
   
    if (tmp.aliasChildren && tmp.aliasChildren.length > 0)
      aliasChildren = aliasChildren.concat(tmp.aliasChildren);

    let routePath = tmp.path || ''
    // if (routePath) {
    //   if (routePath.startsWith('/')) { routePath = (parentPath || '') + tmp.path } else { routePath = (parentPath || '') + '/' + tmp.path }
    // } else {
    //   routePath = parentPath
    // }

    const allow = permissionNames.some(path => {
      return routePath === path
    })

    if (allow) { res.push(tmp) }

    //隐藏的且没有在aliasChildren都是有权限的
    if (!allow && tmp.hidden && aliasChildren.indexOf(tmp.name) == -1) {
      res.push(tmp)
    }

    if (tmp.children) {
      tmp.children = filterPermissionRoute(routePath, permissionNames, tmp.children)
    }
  })
  return res
}
const state = {
  routes: [],
  routeNames: {},
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
    const routeNames = {}

    function _ask(permission_routes) {
      for (let i = 0; i < permission_routes.length; i++) {
        const route = permission_routes[i]
        if (route.name) { routeNames[route.name] = true }
        if (route.children) {
          _ask(route.children)
        }
      }
    }
    _ask(routes)
    state.routeNames = routeNames
  }
}

const actions = {
  async generateRoutes({ commit }, roles) {
    const userName = store.getters.name
    let permissionRouteNames = []
    //if (userName != 'admin') { permissionRouteNames = await getPermission() }
    return new Promise(resolve => {
      let accessedRoutes = asyncRoutes

      // if (userName != 'admin') {
      //   accessedRoutes = filterPermissionRoute(null, permissionRouteNames.data, asyncRoutes)

      // }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
